<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MinIO文件管理器</title>
    <link href="/lib/css/bootstrap.min.css" rel="stylesheet">
    <link href="/lib/css/bootstrap-icons.css" rel="stylesheet">
    <style>
        .file-item {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 10px;
            padding: 10px;
            transition: all 0.3s ease;
            background-color: #fff;
        }
        .file-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        .upload-area {
            border: 2px dashed #007bff;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            background-color: #f8f9fa;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .upload-area:hover {
            background-color: #e9ecef;
            border-color: #0056b3;
        }
        .upload-area.dragover {
            background-color: #cce7ff;
            border-color: #004085;
        }
        .progress-container {
            margin-top: 20px;
        }
        .api-docs-link {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="row">
            <div class="col-12">

                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1><i class="bi bi-cloud-arrow-up"></i> MinIO文件管理器</h1>
                    <div>
                        <button class="btn btn-primary me-2" onclick="showUploadModal()">
                            <i class="bi bi-plus-circle"></i> 上传文件
                        </button>
                        <button class="btn btn-info" onclick="refreshFileList()">
                            <i class="bi bi-arrow-clockwise"></i> 刷新
                        </button>
                    </div>
                </div>

                <!-- 文件上传区域 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5><i class="bi bi-cloud-upload"></i> 文件上传</h5>
                    </div>
                    <div class="card-body">
                        <div id="uploadArea" class="upload-area" ondrop="handleDrop(event)" ondragover="handleDragOver(event)" ondragleave="handleDragLeave(event)">
                            <i class="bi bi-cloud-upload" style="font-size: 48px; color: #007bff;"></i>
                            <h4 class="mt-3">拖拽文件到这里或点击选择文件</h4>
                            <p class="text-muted">支持任意格式的文件上传</p>
                            <input type="file" id="fileInput" multiple style="display: none;" onchange="handleFileSelect(event)">
                        </div>

                        <!-- 进度条 -->
                        <div id="progressContainer" class="progress-container" style="display: none;">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span id="progressText" class="progress-text">上传中...</span>
                                <span id="progressPercent" class="progress-text">0%</span>
                            </div>
                            <div class="progress">
                                <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 文件列表 -->
                <div class="card">
                    <div class="card-header">
                        <h5><i class="bi bi-folder2-open"></i> 文件列表</h5>
                    </div>
                    <div class="card-body">
                        <div id="fileList">
                            <div class="text-center text-muted">
                                <i class="bi bi-hourglass-split" style="font-size: 48px;"></i>
                                <p class="mt-3">正在加载文件列表...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- API文档链接 -->
    <div class="api-docs-link">
        <a href="/swagger-ui.html" class="btn btn-success btn-lg" target="_blank">
            <i class="bi bi-book"></i> API文档
        </a>
    </div>

    <!-- 上传模态框 -->
    <div class="modal fade" id="uploadModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">文件上传选项</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="customFileName" class="form-label">自定义文件名（可选）</label>
                        <input type="text" class="form-control" id="customFileName" placeholder="留空使用原文件名">
                    </div>
                    <div class="mb-3">
                        <label for="asyncUpload" class="form-label">上传方式</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="asyncUpload">
                            <label class="form-check-label" for="asyncUpload">
                                异步上传（大文件推荐）
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="uploadWithOptions()">开始上传</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/lib/js/bootstrap.bundle.min.js"></script>
    <script>
        let selectedFiles = [];
        let uploadModal;

        document.addEventListener('DOMContentLoaded', function() {
            uploadModal = new bootstrap.Modal(document.getElementById('uploadModal'));

            // 绑定上传区域点击事件
            document.getElementById('uploadArea').addEventListener('click', function() {
                document.getElementById('fileInput').click();
            });

            // 初始化存储桶并加载文件列表
            initBucket();
            refreshFileList();
        });

        // 初始化存储桶
        async function initBucket() {
            try {
                await fetch('/api/minio/init', { method: 'POST' });
            } catch (error) {
                console.error('初始化存储桶失败:', error);
            }
        }

        // 刷新文件列表
        async function refreshFileList() {
            try {
                const response = await fetch('/api/minio/files');
                const result = await response.json();

                const fileListElement = document.getElementById('fileList');

                if (result.success && result.data.length > 0) {
                    fileListElement.innerHTML = result.data.map(file => `
                        <div class="file-item">
                            <div class="row align-items-center">
                                <div class="col-md-6">
                                    <h6><i class="bi bi-file-earmark"></i> ${file.fileName}</h6>
                                    <small class="text-muted">
                                        大小: ${formatFileSize(file.size)} |
                                        修改时间: ${new Date(file.lastModified).toLocaleString()}
                                    </small>
                                </div>
                                <div class="col-md-6 text-end">
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-sm btn-outline-primary" onclick="downloadFile('${file.fileName}')">
                                            <i class="bi bi-download"></i> 下载
                                        </button>
                                        <button class="btn btn-sm btn-outline-info" onclick="copyFileUrl('${file.fileName}')">
                                            <i class="bi bi-link-45deg"></i> 复制链接
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" onclick="deleteFile('${file.fileName}')">
                                            <i class="bi bi-trash"></i> 删除
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `).join('');
                } else {
                    fileListElement.innerHTML = `
                        <div class="text-center text-muted p-4">
                            <i class="bi bi-inbox" style="font-size: 48px;"></i>
                            <p class="mt-3">暂无文件</p>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('获取文件列表失败:', error);
                document.getElementById('fileList').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-triangle"></i> 获取文件列表失败
                    </div>
                `;
            }
        }

        // 拖拽处理
        function handleDragOver(event) {
            event.preventDefault();
            document.getElementById('uploadArea').classList.add('dragover');
        }

        function handleDragLeave(event) {
            event.preventDefault();
            document.getElementById('uploadArea').classList.remove('dragover');
        }

        function handleDrop(event) {
            event.preventDefault();
            document.getElementById('uploadArea').classList.remove('dragover');

            selectedFiles = Array.from(event.dataTransfer.files);
            uploadModal.show();
        }

        // 文件选择处理
        function handleFileSelect(event) {
            selectedFiles = Array.from(event.target.files);
            if (selectedFiles.length > 0) {
                uploadModal.show();
            }
        }

        // 显示上传模态框
        function showUploadModal() {
            document.getElementById('fileInput').click();
        }

        // 使用选项上传文件
        async function uploadWithOptions() {
            const customFileName = document.getElementById('customFileName').value;
            const asyncUpload = document.getElementById('asyncUpload').checked;

            uploadModal.hide();

            for (const file of selectedFiles) {
                // 确保文件名不为空
                let fileName = customFileName || file.name;
                if (!fileName || fileName.trim() === '') {
                    fileName = file.name || 'unnamed_file';
                }
                await uploadFile(file, fileName, asyncUpload);
            }

            selectedFiles = [];
            document.getElementById('customFileName').value = '';
            document.getElementById('asyncUpload').checked = false;
        }

        // 上传文件
        async function uploadFile(file, fileName, async) {
            const formData = new FormData();
            formData.append('file', file);
            if (fileName) {
                formData.append('fileName', fileName);
            }

            const endpoint = async ? '/api/minio/upload/async' : '/api/minio/upload';

            try {
                showProgress('正在上传 ' + file.name + '...');

                const response = await fetch(endpoint, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    showProgress('上传完成: ' + file.name, 100);
                    setTimeout(() => {
                        hideProgress();
                        refreshFileList();
                    }, 1000);
                } else {
                    showProgress('上传失败: ' + result.message, 0, true);
                    setTimeout(hideProgress, 3000);
                }
            } catch (error) {
                console.error('上传失败:', error);
                showProgress('上传失败: ' + error.message, 0, true);
                setTimeout(hideProgress, 3000);
            }
        }

        // 下载文件
        function downloadFile(fileName) {
            const encodedFileName = encodeURIComponent(fileName);
            window.open(`/api/minio/download/${encodedFileName}`, '_blank');
        }

        // 删除文件
        async function deleteFile(fileName) {
            if (!confirm('确定要删除文件 "' + fileName + '" 吗？')) {
                return;
            }

            try {
                const encodedFileName = encodeURIComponent(fileName);
                const response = await fetch(`/api/minio/delete/${encodedFileName}`, {
                    method: 'DELETE'
                });

                const result = await response.json();

                if (result.success) {
                    alert('文件删除成功');
                    refreshFileList();
                } else {
                    alert('删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 复制文件URL
        async function copyFileUrl(fileName) {
            try {
                const encodedFileName = encodeURIComponent(fileName);
                const response = await fetch(`/api/minio/url/${encodedFileName}`);

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();

                if (result.success && result.data) {
                    const fileUrl = result.data.fileUrl;

                    // 使用更兼容的复制方法
                    if (navigator.clipboard && window.isSecureContext) {
                        // 现代浏览器安全上下文
                        await navigator.clipboard.writeText(fileUrl);
                        alert('文件链接已复制到剪贴板');
                    } else {
                        // 降级方案：使用传统的复制方法
                        const textArea = document.createElement('textarea');
                        textArea.value = fileUrl;
                        textArea.style.position = 'fixed';
                        textArea.style.left = '-999999px';
                        textArea.style.top = '-999999px';
                        document.body.appendChild(textArea);
                        textArea.focus();
                        textArea.select();

                        try {
                            const successful = document.execCommand('copy');
                            if (successful) {
                                alert('文件链接已复制到剪贴板');
                            } else {
                                throw new Error('复制命令执行失败');
                            }
                        } catch (err) {
                            // 如果复制失败，显示链接让用户手动复制
                            prompt('请手动复制以下链接:', fileUrl);
                        } finally {
                            document.body.removeChild(textArea);
                        }
                    }
                } else {
                    const errorMsg = result.message || '获取文件链接失败';
                    alert('获取文件链接失败: ' + errorMsg);
                }
            } catch (error) {
                console.error('复制链接失败:', error);
                alert('复制链接失败: ' + error.message);
            }
        }

        // 显示进度条
        function showProgress(text, percent = 0, isError = false) {
            const container = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');
            const progressPercent = document.getElementById('progressPercent');

            container.style.display = 'block';
            progressText.textContent = text;
            progressPercent.textContent = percent + '%';
            progressBar.style.width = percent + '%';

            if (isError) {
                progressBar.className = 'progress-bar bg-danger';
            } else {
                progressBar.className = 'progress-bar bg-primary';
            }
        }

        // 隐藏进度条
        function hideProgress() {
            document.getElementById('progressContainer').style.display = 'none';
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html>